<?php

function diffWithFormat($days)
{
    if ($days instanceof \Carbon\Carbon) {
        $days = $days->diffInDays();
    } elseif (!is_numeric($days)) {
        $days = (new \Carbon\Carbon($days))->diffInDays();
    }

    $time = '';

    if ($year = (int)($days / 365)) {
        $time = $year . '年';
    }

    if ($month = (int)(($days - $year * 365) / 30)) {
        $time .= $month . '个月';
    }

    if ($day = ($days - $year * 365) - $month * 30) {
        $time .= $day . '天';
    }

    return $time;
}

function fed($field, $key = null, $left = '', $right = '')
{
    return fe($field, $key, $left, $right, function ($value) {

        return diffWithFormat($value);
    });
}

function fei($field, $key = null, $left = '', $right = '')
{
    return fe($field, $key, $left, $right, function ($value) {

        return implode(', ', $value);
    });
}

function fe($field, $key = null, $left = '', $right = '', Closure $closure = null)
{
    if (is_string($field)) {
        if (('' === $left) && ('' === $right)) {
            return $field;
        }

        return $left. ' ' . $field. ' ' . $right;
    }

    if (\Illuminate\Support\Arr::has($field, $key)) {

        $value = \Illuminate\Support\Arr::get($field, $key);

        if ($value) {
            if (!is_null($closure)) {
                $value = $closure($value);
            }

            if (('' === $left) && ('' === $right)) {
                return $value;
            }

            return $left. ' ' . $value . $right;
        }
    }

    return '';
}

function ft($file, $value, $left = '', $right = '')
{
    if ('' === $value) {
        return '';
    }

    if (('' === $left) && ('' === $right)) {
        return app('field')->get($file)[$value];
    }

    return $left. ' ' . app('field')->get($file)[$value]. ' ' . $right;
}


function fr($field, $key = null, $right = '')
{
    if (!isset($field)) {
        return '';
    }

    if (is_string($field)) {
        if ('' === $right) {
            return $field;
        }
        return $field. '' . $right;
    }
    if (\Illuminate\Support\Arr::has($field, $key)) {

        $value = \Illuminate\Support\Arr::get($field, $key);
        if(is_null($value)||''===$value){
            return $value;
        }

        if ('' === $right) {
            return $value;
        }

        return '' . $value . $right;
    }

    return '';
}

/**
 * 判断是否空数组，,防止空字符串导致打印出问题
 */
function isEmpty($arr){
    if(is_array($arr)){
        $b=true;
        foreach ($arr as $k=>$v){
            if($v&&!is_array($v)&&!trim($v)==''){
                $b=false;
                break;
            }
            return isEmpty($v);
        }
        return $b;
    }else{
        if(!$arr){
            return true;
        }else
            return false;
    }
}

function mb_trim($string, $trim_chars = '\s')

{

    return preg_replace('/^['.$trim_chars.']*(?U)(.*)['.$trim_chars.']*$/u', '\\1',$string);
}